package heap.medium;

import java.util.*;

/**
 * 前K个高频单词
 * 示例 1：
 *
 * 输入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
 * 输出: ["i", "love"]
 * 解析: "i" 和 "love" 为出现次数最多的两个单词，均为2次。
 *     注意，按字母顺序 "i" 在 "love" 之前。
 *  
 *
 * 示例 2：
 *
 * 输入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
 * 输出: ["the", "is", "sunny", "day"]
 * 解析: "the", "is", "sunny" 和 "day" 是出现次数最多的四个单词，
 *     出现次数依次为 4, 3, 2 和 1 次。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/top-k-frequent-words
 */
public class TopKFrequentWords_692 {

    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String, Integer> map = new HashMap<>();
        for (String word : words) {
            map.put(word, map.getOrDefault(word, 0) + 1);
        }
        PriorityQueue<String> minHeap = new PriorityQueue<>((a, b) -> {
            if (map.get(a) == map.get(b))
                return b.compareTo(a);
            else
                return map.get(a) - map.get(b);
        });

        for (String s : map.keySet()) {
            minHeap.offer(s);
            if (k < minHeap.size())
                minHeap.poll();
        }
        String[] str = new String[minHeap.size()];
        int n = minHeap.size();
        for (int i = n - 1; i >= 0; i--){
            str[i] = minHeap.poll();
        }
        return Arrays.asList(str);
    }

    public static void main(String[] args) {
        TopKFrequentWords_692 tk = new TopKFrequentWords_692();
        tk.topKFrequent( new String[]{"the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"}, 4);
    }
}
